package com.epro.dx.activity.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.CheckoutActivity;
import com.epro.dx.activity.DetailActivity;
import com.epro.dx.activity.DiscountActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.creditcard.AddCreditCardActivity;
import com.epro.dx.activity.creditcard.CreditCardListActivity;
import com.epro.dx.activity.myaddress.EditAddressActivity;
import com.epro.dx.activity.myaddress.MyAddressBookActivity;
import com.epro.dx.adapter.ShoppingCartAdapter;
import com.epro.dx.adapter.ShoppingCartAdapter.FavoriteBtnListenner;
import com.epro.dx.adapter.ShoppingCartAdapter.OnProductChangeListenner;
import com.epro.dx.listenner.GetCreditCardInfoListenner;
import com.epro.dx.listenner.PaymentMethodDialogOnClickListenner;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.ClickUtils;
import com.epro.dx.util.GetCreditCardInfoAsyncTask;
import com.epro.dx.util.PaymentMethodDialogUtils;
import com.epro.dx.widget.MyListView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.constants.ServerConstant.ReturnCode.User;
import com.weipu.common.facade.content.api.MyCartService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.CouponModel;
import com.weipu.common.facade.model.CreateOrderStatus;
import com.weipu.common.facade.model.CreditCardInfo;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.OrderPayModel;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.OrderProductModel.SalesLimit;
import com.weipu.common.facade.model.PreviewOrderModel;
import com.weipu.common.facade.model.SalesLimitModel;
import com.weipu.common.facade.model.SimpleCreditCard;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NetWorkUtil;
import com.weipu.common.util.StringUtil;

/**
 * @创建者： TonyYang
 * @创建时间：2015-8-4下午3:35:05
 * @描述：订单确认页面 @ svn提交者：$Author$ @ 提交时间: $Date$ @ 当前版本: $Rev$
 *
 */
public class OrderPlaceActivity extends BaseFragmentActivity implements
        FavoriteBtnListenner, OnProductChangeListenner {

    protected static final String TAG = "OrderPlaceActivity";

    // 收货人姓名
    private TextView consignee;

    // 收货地址
    private TextView address;

    // 优惠价格
    private TextView superSaver;

    // 订单数量
    private TextView orderNumber;

    // 订单列表
    private MyListView orderList;

    // 应付总额
    private TextView subTotal;

    // 优惠额度
    private TextView discount;

    // 实付总额
    private TextView grandTotal;

    // 点击按钮确认订单进入支付页面
    private Button confirmOrder;

    private Button toAddAddressBtn;

    private TextView freeShippingPriceTv;

    private RelativeLayout disCountLayout;

    private RelativeLayout disCountTotalLayout;

    // 商品订单信息集合
    private ArrayList<OrderProductModel> orderProductModels;

    // 地址信息展示栏
    private RelativeLayout chooseAddress;

    private boolean isPriceChange;

    private boolean isLimit;

    /**
     * saleLimit的数据存储
     */
    private Map<Integer, SalesLimitModel> limitMap = new HashMap<Integer, SalesLimitModel>();

    private ShoppingCartAdapter orderPlaceItemAdapter;

    private AddressModel receiveAddress;

    private int densityDpi;

    private PreviewOrderModel previewOrderModel;

    private String couponCode = null;

    private boolean isCouponCode;

    // 是否需要清除服务端购物车数据
    private boolean isClearCart;

    // 已经使用的手动CouponCode

    private String appliedCouponCode = null;

    private ScrollView orderDetail;

    private LinearLayout confirm_layout;

    private boolean isPreviewOrder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 集成GA
        tracker = DXApplication.getContext()
                .getTracker(TrackerName.APP_TRACKER);
        eventBuilder = new HitBuilders.EventBuilder();
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 关联布局文件
        setContentView(R.layout.activity_order_place);
        // 设置标题与返回按钮
        setTitleContent("Checkout");
        setLeftBtnContent(true, -1);

        // 初始化控件布局
        initView();
        // 获取跳转过来时携带的数据
        initOrderData(savedInstanceState);

        if (null == orderProductModels || orderProductModels.isEmpty()) {
            orderProductModels = new ArrayList<OrderProductModel>();
        }
        // else {
        // isPreviewOrder=true;
        // // AsyncTaskUtil.executeTask(new PreviewOrderTask(false, null));
        // }
        showDatas();

        // // 获取地址信息
        // new GetAddressAsyk().execute();
        AsyncTaskUtil.executeTask(new GetAddressAsyk());

        // 加载事件
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        tracker.setScreenName("CheckOut");
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ServerConstant.Parameter.CHOOSE_ADDRESS_CODE
                && data != null) {
            AddressModel addModel = (AddressModel) data
                    .getSerializableExtra("addressModel");
            refreshAddress(addModel);
            receiveAddress = addModel;

        }
        if (requestCode == ServerConstant.Parameter.ADD_ADDRESS_CODE
                && null != data) {
            AddressModel addressModel = (AddressModel) data
                    .getSerializableExtra("addressModel");
            if (null != addressModel) {
                refreshAddress(addressModel);
                receiveAddress = addressModel;
            }
        }

        if (requestCode == ServerConstant.Parameter.CHOOSE_COUPON_CODE
                && null != data) {
            couponCode = data.getStringExtra("CouponCode");
            isCouponCode = data.getBooleanExtra("IsCouponCode", false);
            Logger.i("isCoupon", couponCode + " onActivityResult "
                    + isCouponCode);
            // previewOrderModel = (PreviewOrderModel) data
            // .getSerializableExtra("PreviewOrderModel");
            AsyncTaskUtil.executeTask(new PreviewOrderTask(false, null));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 点击事件
    OnClickListener myClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (ClickUtils.isFastDoubleClick()) {
                return;
            }
            switch (v.getId()) {
                case R.id.rl_order_place_address:
                    // 集成GA
                    eventBuilder.setCategory("Click").setAction("Choose address");
                    tracker.send(eventBuilder.build());
                    // 进入选择收货地址页面
                    Intent i = new Intent(OrderPlaceActivity.this,
                            MyAddressBookActivity.class);
                    i.putExtra("fromChooseAdd", true);

                    if(null!=choosedAddressModel){
                        i.putExtra("ChooseAddressID", choosedAddressModel.getAddressID());
                    }
                    startActivityForResult(i,
                            ServerConstant.Parameter.CHOOSE_ADDRESS_CODE);
                    break;
                case R.id.btn_order_place_confirm:

                    // 集成GA
                    eventBuilder.setCategory("Click").setAction("Place order");
                    tracker.send(eventBuilder.build());
                    if (null == receiveAddress) {
                        AlertToast.alert(OrderPlaceActivity.this,
                                getString(R.string.choose_address_suggest));
                        return;
                    }
                    // 进入支付流程  首先校验产品库存
                    AsyncTaskUtil.executeTask(new CheckDataEffective());
                    break;
                case R.id.no_address_add_address_btn:
                    // 集成GA
                    eventBuilder.setCategory("Click").setAction("Add address");
                    tracker.send(eventBuilder.build());
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(),
                            EditAddressActivity.class);
                    intent.putExtra("from", "addAddress");
                    // intent.putExtra("countryModel", countryModel);
                    startActivityForResult(intent,
                            ServerConstant.Parameter.ADD_ADDRESS_CODE);
                    break;
                case R.id.discount_layout:
                    Intent disIntent = new Intent();
                    disIntent.setClass(getApplicationContext(),
                            DiscountActivity.class);
                    if (null != previewOrderModel) {
                        disIntent.putParcelableArrayListExtra("UseableCoupon",
                                previewOrderModel.getUsableCoupons());
                        // 暂未考虑到库存不足产品的处理
                        disIntent
                                .putParcelableArrayListExtra(
                                        ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                                        previewOrderModel.getLines());
                    } else {
                        disIntent
                                .putParcelableArrayListExtra(
                                        ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                                        orderProductModels);

                    }
                    if (isCouponCode && null != couponCode
                            && !"".equals(couponCode)) {
                        disIntent.putExtra("CouponCode", couponCode);
                    }
                    startActivityForResult(disIntent,
                            ServerConstant.Parameter.CHOOSE_COUPON_CODE);
                    break;

                default:
                    break;
            }
        }
    };

    private Tracker tracker;

    private EventBuilder eventBuilder;

    private TextView scTv;
    private TextView scTipTv;

    private CheckBox imgsc;

    private View scdiv;

    private View scparent;


    /**
     * 事件的初始化加载
     */
    private void initEvent() {
        toAddAddressBtn.setOnClickListener(myClickListener);
        // 收获地址栏的点击事件
        chooseAddress.setOnClickListener(myClickListener);
        // 确认按钮的点击事件
        confirmOrder.setOnClickListener(myClickListener);
        disCountLayout.setOnClickListener(myClickListener);
        // 订单商品列表的点击事件
        orderList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                // 点击显示商品详情页面
                OrderProductModel cartItem = (OrderProductModel) orderPlaceItemAdapter
                        .getItem(position);

                Intent intent = new Intent(OrderPlaceActivity.this,
                        DetailActivity.class);
                Bundle data = new Bundle();

                data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                        cartItem.getSku());

                data.putString(
                        ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                        ServerConstant.ActionConstant.ACTION_MYCART);
                data.putString(
                        ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                        ServerConstant.ActionConstant.ACTION_MYCART);

                intent.putExtras(data);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取用户收获地址
     *
     * @author HF
     *
     */
    private class GetAddressAsyk extends BaseNeedReLoginTask {

        @Override
        protected void onPreExecute() {
            // 开始加载，显示加载视图
            // showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                // AddressModel defaultAddress = null;
                // 获取CustomerId
                String customerid = GlobalConfig.getInstance()
                        .getUserSessionCfg().getCustomerid();
                if (null == customerid || "".equals(customerid)) {
                    customerid = StringUtil.getConfig(
                            ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
                            "0");
                }
                long cid = Long.parseLong(customerid);
                // receiveAddress = ProviderFactory.createUserServiceProvider()
                // .GetDefaultAddress(cid, 1);
                List<AddressModel> defaultModels = ProviderFactory
                        .createUserServiceProvider().GetAddresses(cid, 1, 1, 10,ActivityUtil.getCustomerToken());
                if (null != defaultModels && defaultModels.size() >= 1) {
                    receiveAddress = defaultModels.get(0);
                }
            } catch (DxException e) {
                return e.getErrCode();
            }

            // return requestLimit(false);
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (!isFinishing()) {
                // hideWaitingDialog();
                // if(!isPreviewOrder){
                hideAllLayout(orderDetail);
                // }
                if (null == result) {
                    orderPlaceItemAdapter.notifyDataSetChanged();
                    // 成功获取默认地址
                    if (null != receiveAddress) {
                        refreshAddress(receiveAddress);
                    } else {
                        chooseAddress.setVisibility(View.GONE);
                        toAddAddressBtn.setVisibility(View.VISIBLE);
                    }
                } else if(!isRelogin){
                    AlertToast.alert(OrderPlaceActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }

            }
        }

        @Override
        protected Context setContext() {
            return OrderPlaceActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new GetAddressAsyk();
        }

    }

    private void refreshAddress(AddressModel addModel) {
        if(addModel==null){
            return;
        }
        choosedAddressModel = addModel;
        chooseAddress.setVisibility(View.VISIBLE);
        toAddAddressBtn.setVisibility(View.GONE);
        AddressModel.Address myAddress = addModel.getAddress();
        if (null != address) {
            // 收获人姓名
            consignee.setText(myAddress.getFirstName() + ","
                    + myAddress.getLastName());
            StringBuilder getProductAddress = new StringBuilder();
            String street2 = myAddress.getStreet2();
            if (null != street2 && !"".equals(street2)) {
                getProductAddress.append(street2).append(",");
            }
            if(null!=myAddress){
                getProductAddress.append(myAddress.getStreet1()).append(",")
                        .append(myAddress.getCity()).append(",")
                        .append(myAddress.getState()).append(",")
                        .append(addModel.getCountryName()).append("(")
                        .append(myAddress.getPostalCode()).append(")");
            }
            // 收货地址
            address.setText(getProductAddress);
        }

    }

    /**
     * 加载订单信息
     *
     * @param savedInstanceState
     */
    private void initOrderData(Bundle savedInstanceState) {
        intent = getIntent();
        if (intent != null) {
            orderProductModels = intent
                    .getParcelableArrayListExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP);
            // previewOrderModel = (PreviewOrderModel) intent
            // .getSerializableExtra("PreviewOrderModel");
            isClearCart = intent.getBooleanExtra("isClearCart", false);
        }
        if (savedInstanceState != null
                && savedInstanceState.containsKey("orderProducts")) {
            orderProductModels = savedInstanceState
                    .getParcelableArrayList("orderProducts");
            // previewOrderModel = (PreviewOrderModel) savedInstanceState
            // .getSerializable("PreviewOrderModel");
        }

        // if(null!=previewOrderModel){
        // orderProductModels=previewOrderModel.getLines();
        // orderProductModels.addAll(previewOrderModel.getAllGiftSkus());
        // }
    }

    /**
     * 数据的处理与显示
     */
    private void showDatas() {
        // 订单总数
        orderNumber.setText(getString(R.string.order_item_title,
                orderProductModels.size() + ""));
        // orderPlaceItemAdapter = new ShoppingCartAdapter(
        // getApplicationContext(), this, orderProductModels, limitMap,
        // false,densityDpi,NetWorkUtil.isWifi(getApplicationContext()));
        orderPlaceItemAdapter = new ShoppingCartAdapter(
                getApplicationContext(), this, orderProductModels, false,
                densityDpi, NetWorkUtil.isWifi(getApplicationContext()));
        String currencyCodeStr = intent.getStringExtra("CurrencyCodeStr");
        if (!TextUtils.isEmpty(currencyCodeStr)) {
            orderPlaceItemAdapter.setCurrencyCode(null, currencyCodeStr);
        }
        orderList.setAdapter(orderPlaceItemAdapter);
        orderPlaceItemAdapter.setFavoriteListenner(this);
        orderPlaceItemAdapter.notifyDataSetChanged();
        // // 显示金额
        // refreshUi();
        // refreshMoney();
        String currencyCode = intent
                .getStringExtra(ServerConstant.Parameters.PARAMETERS_CURRENCYCODESTR);
        double discountMoney = intent.getDoubleExtra(
                ServerConstant.Parameters.PARAMETERS_DISCOUNT, 0);
        grandTotal.setText(currencyCode
                + String.format("%.2f", intent.getDoubleExtra(
                ServerConstant.Parameters.PARAMETERS_GRANDTOTAL, 0)));
        subTotal.setText(currencyCode
                + String.format("%.2f", intent.getDoubleExtra(
                ServerConstant.Parameters.PARAMETERS_SUBTOTAL, 0)));
        if (discountMoney > 0) {
            disCountTotalLayout.setVisibility(View.VISIBLE);
            discount.setText("-" + currencyCode
                    + String.format("%.2f", discountMoney));
        } else {
            disCountTotalLayout.setVisibility(View.GONE);
        }

        float sc = intent.getFloatExtra(ServerConstant.Parameters.PARAMETERS_RETURNSC, 0f);
        showScText(currencyCode,sc);

    }

    private void showScText(String codeStr,float sc) {
        if(sc <=0f){
            return ;
        }

        scparent.setVisibility(View.VISIBLE);
        scdiv.setVisibility(View.VISIBLE);
        scTipTv.setVisibility(View.GONE);

        scTv.setText(codeStr+sc+" SC");

        //加粗，改变颜色
        String boldString = codeStr+sc;
        String scString = getString(R.string.sc_tip, boldString);
        int start = scString.lastIndexOf(boldString);
        int end = start + boldString.length();
        SpannableStringBuilder style = new SpannableStringBuilder(scString);
        style.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_grode)), start, end+3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        scTipTv.setText(style);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList("orderProducts", orderProductModels);
        // outState.putSerializable("PreviewOrderModel", previewOrderModel);
        super.onSaveInstanceState(outState);
    }

    /**
     * 初始化控件布局
     */
    private void initView() {
        densityDpi = getDensityDpi();
        // 查找关联控件
        consignee = (TextView) findViewById(R.id.tv_order_place_consignee);
        address = (TextView) findViewById(R.id.tv_order_place_address);
        toAddAddressBtn = (Button) findViewById(R.id.no_address_add_address_btn);
        consignee = (TextView) findViewById(R.id.tv_order_place_consignee);
        superSaver = (TextView) findViewById(R.id.tv_order_place_supersaver);
        orderNumber = (TextView) findViewById(R.id.tv_order_place_oderitems_number);
        subTotal = (TextView) findViewById(R.id.tv_order_place_subtotal);
        discount = (TextView) findViewById(R.id.tv_order_place_discount);
        disCountTotalLayout = (RelativeLayout) findViewById(R.id.total_discount_layout);
        grandTotal = (TextView) findViewById(R.id.tv_order_place_grandtotal);
        confirmOrder = (Button) findViewById(R.id.btn_order_place_confirm);
        chooseAddress = (RelativeLayout) findViewById(R.id.rl_order_place_address);
        orderList = (MyListView) findViewById(R.id.lv_order_place_oderitems_list);
        freeShippingPriceTv = (TextView) findViewById(R.id.tv_order_place_freeshipp_price);
        freeShippingPriceTv.setText(getString(R.string.shpping_price, "0.00"));
        disCountLayout = (RelativeLayout) findViewById(R.id.discount_layout);
        orderDetail = (ScrollView) findViewById(R.id.order_place_detail);
        confirm_layout = (LinearLayout) findViewById(R.id.btn_order_place_confirm_layout);

        scTv = (TextView) findViewById(R.id.tv_order_place_sc);
        imgsc = (CheckBox )findViewById(R.id.img_order_place_sc);
        scparent = findViewById(R.id.rl_order_place_scparent);

        scdiv = findViewById(R.id.v_order_place_scdiv);
        scTipTv = (TextView) findViewById(R.id.tv_order_place_sctip);
        scparent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                imgsc.setChecked(!imgsc.isChecked());

            }
        });
        imgsc.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                scTipTv.setVisibility(isChecked?View.VISIBLE:View.GONE);
            }
        });
    }

    @Override
    public void favoriteBtnOnclick(int sku, int position) {
        addWishList(sku, position);

    }

    /**
     * 点击添加到收藏夹
     *
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void addWishList(int sku, int position) {
        if (sku > 0) {
            // 如果未登录，则需要跳转到登录界面
            if (!ActivityUtil.isLogin(this)) {
                gotoLogin();
                return;
            }
            AsyncTaskUtil.executeTask(new AddToWishListAsyncTask(sku, "",
                    position));
        }
        // 产品无效
        else {
            AlertToast.alert(this, R.string.invalid_data);
        }

    }

    private void gotoLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        Bundle data = new Bundle();
        // 设置返回参数,登录成功后需要返回到详情界面
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_NEWMAIN);
        intent.putExtras(data);
        startActivity(intent);
        finish();
    }

    /**
     * 添加到购物车任务
     *
     * @author hf
     * @version [版本号, 2015-8-5]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    protected class AddToWishListAsyncTask extends
            BaseNeedReLoginTask {

        private final int sku;

        private final String source;

        private final int position;
        String userName;

        public AddToWishListAsyncTask(int sku, String source, int position) {
            this.sku = sku;
            this.source = source;
            this.position = position;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                userName = StringUtil.getConfig(OrderPlaceActivity.this,
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                ProviderFactory.createUserServiceProvider().addWishlistForUser(sku, source,
                        ActivityUtil.getCustomerID(),ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyCartActivity", "AddToWishListAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
                // hideWaitingDialog();
                hideAllLayout(orderDetail);
                confirm_layout.setVisibility(View.VISIBLE);
            }
            if ("0".equals(result)) {
                OrderProductModel opModel = orderProductModels.get(position);
                opModel.setIsFavorite("true");
                StringUtil.saveConfig(opModel.getSku() + "", userName);
                com.epro.dx.util.GlobalConfig.getInstance()
                        .setShoppingCartChange(true);
                if (!isFinishing()) {
                    AlertToast.alert(OrderPlaceActivity.this,
                            R.string.user_collection_add_success);
                    orderPlaceItemAdapter.notifyDataSetChanged();
                }
            } else if(!isRelogin){
                // 数据被用户清除后 用户点击已收藏的产品 将按钮标红
                if (User.WISHLIST_ADD_ERROR.equals(result)) {
                    OrderProductModel opModel = orderProductModels
                            .get(position);
                    opModel.setIsFavorite("true");
                    StringUtil.saveConfig(opModel.getSku() + "", userName);
                    if (!isFinishing()) {
                        orderPlaceItemAdapter.notifyDataSetChanged();
                    }
                }
                if (!isFinishing()) {
                    AlertToast.alert(OrderPlaceActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }

            }
        }

        @Override
        protected Context setContext() {
            return OrderPlaceActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new AddToWishListAsyncTask(sku, source, position);
        }
    }

    public String requestLimit(boolean isOrderConfirm) {
        if (null != orderProductModels && orderProductModels.size() > 0) {
            try {
                // 遍历所有产品对象
                ArrayList<Integer> skuList = new ArrayList<Integer>(
                        orderProductModels.size());
                for (int i = 0; i < orderProductModels.size(); i++) {
                    if (orderProductModels.get(i).isGift()) {
                        continue;
                    }
                    skuList.add(orderProductModels.get(i).getSku());
                }
                // 调用库存接口
                Map<Integer, SalesLimitModel> tmpMap = ProviderFactory
                        .createProductProvider().getSaleslimit(skuList);
                if (null != tmpMap && !tmpMap.isEmpty()) {
                    limitMap.clear();
                    limitMap.putAll(tmpMap);
                }
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e(TAG, "SaleLimitAsyncTask", e);
            }
        }
        if (isOrderConfirm) {
            updateNewPrice();
        }
        return null;
    }

    /**
     * PayPal支付流程
     */
    private void payPalPayment(){
        Intent intent = new Intent(OrderPlaceActivity.this,
                CheckoutActivity.class);
        // 传递一个标识，表示从mycartActivity付款的，此时付款完成后需要删除购物车的商品
        intent.putExtra(
                ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                ServerConstant.ActionConstant.FORM_MYCART_ACTIVITY);
        // 检查列表中是否存赠送sku，有就清除掉
        clearGiftSku();
        intent.putParcelableArrayListExtra(
                ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                orderProductModels);
        intent.putExtra("Address", receiveAddress);
        // 加入是否需要清除服务端购物车数据标记
        intent.putExtra("isClearCart", isClearCart);
        // 订单使用的的手动Coupon
        intent.putExtra("CouponCode", appliedCouponCode);
        Logger.i(TAG, "address: " + receiveAddress.toString());
        startActivity(intent);
        finish();
    }

    /**
     * 校验数据有效性
     *
     * @author hf
     * @version [版本号, 2015-8-6]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    class CheckDataEffective extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            isPriceChange = false;
            isLimit = false;
            confirmOrder.setEnabled(false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return requestLimit(true);
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
                confirmOrder.setEnabled(true);
                // hideWaitingDialog();
                hideAllLayout(orderDetail);
                confirm_layout.setVisibility(View.VISIBLE);
                if (null != result) {
                    AlertToast.alert(OrderPlaceActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                } else {
                    if (isLimit) {
                        AlertToast.alert(OrderPlaceActivity.this,
                                R.string.goods_sold_out);
//						refreshUi();
                        orderPlaceItemAdapter.notifyDataSetChanged();
                    } else {
                        int currentVersion = android.os.Build.VERSION.SDK_INT;
                        if(14<=currentVersion&&currentVersion<19){
                            //4.4以下版本不支持PayPal
                            AsyncTaskUtil.executeTask(new CreditCardCreateOrder());
                            return;
                        }
//						showChoosePaymentWindow();
                        PaymentMethodDialogUtils payMethodUtils=new PaymentMethodDialogUtils(new PaymentMethodDialogOnClickListenner() {

                            @Override
                            public void onPayPalClick() {
                                payPalPayment();
                            }

                            @Override
                            public void onCreditCardClick() {
                                //信用卡支付需要先创建订单 然后获取信用卡列表信息
                                AsyncTaskUtil.executeTask(new CreditCardCreateOrder());
                            }
                        });
                        payMethodUtils.showChoosePaymentWindow(OrderPlaceActivity.this);
                    }
                }
            }
        }

    }



    /**
     * 创建订单
     *
     * @author hf
     * @version [版本号, 2016-2-24]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    class CreditCardCreateOrder extends BaseNeedReLoginTask {
        private CreateOrderStatus createOrderStatus;
        MyCartService myCartService = ProviderFactory
                .createMyCartServiceDBProvider();
        private ArrayList<OrderProductModel> orderProductModelresults;
        @Override
        protected void onPreExecute() {
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                createOrderStatus = ProviderFactory
                        .createOrderServiceProvider().createOrder(
                                getOrderPayModel());
                orderProductModelresults = myCartService
                        .selectMenusList(OrderPlaceActivity.this, "_id desc");
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (!isFinishing()) {
                if ("0".equals(result) && null != createOrderStatus) {
                    // 首先查询本地数据库中的商品数据,
//					ArrayList<OrderProductModel> orderProductModelresults = myCartService
//							.selectMenusList(OrderPlaceActivity.this, "_id desc");
                    if (orderProductModelresults != null
                            && orderProductModelresults.size() > 0) {
                        // 删除本地购物车数据，服务端数据不做处理
                        for (int i = 0; i < orderProductModelresults.size(); i++) {
                            int id = orderProductModelresults.get(i).getId();
                            myCartService.deleteById(OrderPlaceActivity.this, id);
                        }
                    }
                    //获取信用卡列表信息
                    AsyncTaskUtil.executeTask(new GetCreditCardInfoAsyncTask(new GetCreditCardInfoListenner() {

                        @Override
                        public void onPreGetInfo() {
                            showLoadingLayout(null);

                        }

                        @Override
                        public void onGetInfoComplect(
                                CreditCardInfo creditCardInfo) {
                            ArrayList<SimpleCreditCard> simpleCreditCards = (ArrayList<SimpleCreditCard>) creditCardInfo
                                    .getsCreditCards();
                            Intent intent = new Intent();
                            String type = creditCardInfo.getGatewayType();
                            if (null == simpleCreditCards || simpleCreditCards.size() == 0) {
                                intent.setClass(OrderPlaceActivity.this, AddCreditCardActivity.class);
                                intent.putExtra("fromPage", "toPay");
                            } else {
                                intent.setClass(OrderPlaceActivity.this, CreditCardListActivity.class);
                                intent.putParcelableArrayListExtra("CreditCards",
                                        simpleCreditCards);
                            }
                            intent.putParcelableArrayListExtra("Lines", (ArrayList<Lines>) getGoods());
                            intent.putExtra("CardFlow", type);
                            intent.putExtra("CouponCode", couponCode);
                            intent.putExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER, createOrderStatus.getOrderNumber());
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onGetInfoFinish() {
                            hideAllLayout(orderDetail);
                        }

                    }, OrderPlaceActivity.this,1));
                }else if(!isRelogin){
                    hideAllLayout(orderDetail);
                    AlertToast.alert(OrderPlaceActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }

        @Override
        protected Context setContext() {
            return OrderPlaceActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new CreditCardCreateOrder();
        }

    }

    /**
     * 获取购买的产品
     * @return
     */
    private List<Lines> getGoods(){
        List<Lines> items = new ArrayList<Lines>();
        for (int i = 0; i < orderProductModels.size(); i++) {
            Lines goods = new Lines();
            OrderProductModel opm=orderProductModels.get(i);
            goods.setSku(opm.getSku());
            goods.setName(opm.getShortHeadLine1());
            goods.setOrderedQty(opm.getQuantity());
            goods.setQty(opm.getQuantity());
            goods.setUnitPrice(opm.getPrice());
            goods.setSellingPrice(opm.getPrice());
            items.add(goods);
        }
        return items;
    }

    /**
     * 获取创建订单的PayModel
     * @return
     */
    private OrderPayModel getOrderPayModel(){
        OrderPayModel orderPayModel=new OrderPayModel();
        orderPayModel.setShippingAddress(ActivityUtil.getShipAddress(receiveAddress));
        orderPayModel.setLines(getGoods());
        orderPayModel.setCustomerID(ActivityUtil.getCustomerID()+"");
        orderPayModel.setDevice("Android_Phone");
        orderPayModel.setCouponCode(couponCode);
        orderPayModel.setIsClearCart(isClearCart);
        orderPayModel.setToken(ActivityUtil.getCustomerToken());
        return orderPayModel;
    }


    /**
     * 清除列表中赠送的sku
     */
    public void clearGiftSku(){
        for (int i = 0; i < orderProductModels.size(); i++) {
            if (orderProductModels.get(i).isGift()) {
                orderProductModels.remove(i);
            }
        }
    }

    /**
     * 更新产品最新价格
     */
    private void updateNewPrice() {
        // 遍历更新价格
        if (null != limitMap) {
            SalesLimitModel tmpLitmodel = null;
            for (int i = 0; i < orderProductModels.size(); i++) {
                OrderProductModel orderProModel = orderProductModels.get(i);
                if (orderProModel != null) {
                    tmpLitmodel = limitMap.get(orderProductModels.get(i)
                            .getSku());
                    if (null == tmpLitmodel) {
                        continue;
                    }
                    // 如果价格相等也忽略不用更新 (由于精度原因，忽略十万分之一的差异)
                    if (Math.abs(orderProModel.getPrice()
                            - tmpLitmodel.getUpdatePrice()) > 0.00001) {
                        orderProductModels.get(i).setPrice(
                                tmpLitmodel.getUpdatePrice());
                        isPriceChange = true;
                    }

                    if (tmpLitmodel.getLimit() != -1
                            && tmpLitmodel.getLimit() < orderProModel
                            .getQuantity()) {
                        isLimit = true;
                    }
                }

            }
        }
    }

    /**
     * 刷新UI数据
     */
	/*public void refreshUi() {
		orderPlaceItemAdapter.notifyDataSetChanged();
		// grandTotal.setText(grandTotalValue+"");
		// subTotal.setText(
		// -----------修改：使用服务端返回的结算金额信息----------------
		// grandTotal.setText(getString(R.string.shpping_price,
		// getGrandTotal()));
		// subTotal.setText(getString(R.string.shpping_price, getGrandTotal()));
		// AsyncTaskUtil.executeTask(new PreviewOrder());
	}*/

    /**
     * 刷新金额
     */
    private void refreshMoney() {
        if (null != previewOrderModel) {
            String currencyCode = previewOrderModel.getCurrencyCodeStr();
            double discountMoney = previewOrderModel.getAllDiscountTotal();
            grandTotal.setText(currencyCode
                    + String.format("%.2f", previewOrderModel.getGrandTotal()));
            subTotal.setText(currencyCode
                    + String.format("%.2f", previewOrderModel.getGoodsTotal()));
            if (discountMoney > 0) {
                disCountTotalLayout.setVisibility(View.VISIBLE);
                discount.setText("-" + currencyCode
                        + String.format("%.2f", discountMoney));
            } else {
                disCountTotalLayout.setVisibility(View.GONE);
            }

            float sc = previewOrderModel.getExpectReturnSCAmount();

            showScText(previewOrderModel.getCurrencyCodeStr(),sc);

        }

    }

    /**
     * 刷新 产品列表
     */
    private void refreshProductList() {
        if (null != previewOrderModel) {
            orderProductModels.clear();
            List<OrderProductModel> lines = previewOrderModel.getLines();
            if (null != lines) {
                orderProductModels.addAll(lines);
            }
            if (orderProductModels.size() > 0) {
                orderPlaceItemAdapter.setCurrencyCode(
                        previewOrderModel.getCurrencyCode(),
                        previewOrderModel.getCurrencyCodeStr());
            }
            List<OrderProductModel> giftModel = previewOrderModel
                    .getAllGiftSkus();
            if (null != giftModel && giftModel.size() > 0) {
                orderProductModels.addAll(giftModel);
            }
            orderPlaceItemAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void deleteProductItem(OrderProductModel productModel) {

    }

    private boolean isAdd = false;

    private Intent intent;

    private AddressModel choosedAddressModel;

    @Override
    public void changeProductNum(OrderProductModel productModel, boolean isAdd,
                                 boolean islimitChange) {
        this.isAdd = isAdd;
        if (orderProductModels != null && orderProductModels.size() > 0
                && !islimitChange) {
            AsyncTaskUtil
                    .executeTask(new PreviewOrderTask(false, productModel));
        }
    }

    /**
     * @author Tony 描述：请求服务器获取购物车中商品的价格信息
     */
    class PreviewOrderTask extends AsyncTask<Void, Void, String> {
        private PreviewOrderModel previewOrder;
        private boolean isSubmitOrder;
        private OrderProductModel changedProductModel;

        public PreviewOrderTask(boolean isSubmitOrder,
                                OrderProductModel changedProductModel) {
            this.isSubmitOrder = isSubmitOrder;
            this.changedProductModel = changedProductModel;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            // 调用PreviewOrder接口获取商品金额信息
            List<Lines> lines = new ArrayList<Lines>();
            if (orderProductModels != null && orderProductModels.size() > 0) {
                clearGiftSku();
                for (int i = 0; i < orderProductModels.size(); i++) {
                    Lines line = new Lines();
                    OrderProductModel orderProductModel = orderProductModels
                            .get(i);
                    line.setSku(orderProductModel.getSku());
                    line.setQty(orderProductModel.getQuantity());
                    line.setSellingPrice(orderProductModel.getPrice());
                    lines.add(line);
                }
            }
            try {
                previewOrder = ProviderFactory.createCouponServiceProvider()
                        .PreviewOrder(Integer.parseInt(getCustomerID()), null,
                                0, lines, couponCode, "USD",ActivityUtil.getCustomerToken(), null);
            } catch (DxException e) {
                return e.getErrCode();
            }
            if (isSubmitOrder) {
                if (null != previewOrder) {
                    List<OrderProductModel> orModels = previewOrder.getLines();
                    if (null != orModels) {
                        for (int i = 0; i < orModels.size(); i++) {
                            SalesLimit s = orModels.get(i).getSalesLimit();
                            if (s != null && s.getDistributionPolicy() != 2) {
                                return "1";
                            }
                        }
                    }
                }
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
                if ("0".equals(result) || "1".equals(result)) {
                    hideAllLayout(orderDetail);
                    confirm_layout.setVisibility(View.VISIBLE);
                    if (null != previewOrder) {
                        previewOrderModel = previewOrder;
                        refreshMoney();
                        refreshProductList();
                        // 取手动Coupon用于下单
                        appliedCouponCode = null;
                        ArrayList<CouponModel> appliedCoupons = previewOrderModel
                                .getAppliedCoupons();
                        if (appliedCoupons != null) {
                            for (int i = 0; i < appliedCoupons.size(); i++) {
                                CouponModel couponModel = appliedCoupons.get(i);
                                if (!couponModel.isAutomatic()) {
                                    appliedCouponCode = couponModel
                                            .getCouponCode();
                                }
                            }
                        }
                    }
                    if ("1".equals(result)) {
                        AlertToast.alert(OrderPlaceActivity.this,
                                R.string.goods_sold_out);
                    }
                } else if(!isRestricted()){
                    AlertToast.alert(OrderPlaceActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    // 出现异常，将商品数量复原
                    if (orderProductModels != null
                            && orderProductModels.size() != 0
                            && changedProductModel != null) {
                        for (int i = 0; i < orderProductModels.size(); i++) {
                            OrderProductModel model = orderProductModels.get(i);
                            if (model.getSku() == changedProductModel.getSku()) {
                                model.setQuantity(isAdd ? model.getQuantity() - 1
                                        : model.getQuantity() + 1);
                            }
                        }
                        hideAllLayout(orderDetail);
                        confirm_layout.setVisibility(View.VISIBLE);
                        refreshProductList();
                    } else {
                        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE
                                .equals(result)) {
                            showErrorLayout(orderDetail,
                                    R.string.internet_error,
                                    R.string.internet_suggest,
                                    R.drawable.no_internet);
                        } else {
                            showErrorLayout(orderDetail, R.string.server_busy,
                                    R.string.server_suggest,
                                    R.drawable.no_internet);
                        }
                        confirm_layout.setVisibility(View.GONE);
                        retryBtn.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // 错误页面重试按钮点击操作
                                AsyncTaskUtil.executeTask(new PreviewOrderTask(
                                        isSubmitOrder, changedProductModel));
                            }
                        });
                    }
                }
            }

            super.onPostExecute(result);
        }

    }

}
